package net.maku.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import net.maku.bean.model.MyException;

public class WeChatUtil {

    public static String jscode2session(String appid, String secret, String code) throws IOException {
        
    	String JSCODE_TO_SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session?";
    	String url = JSCODE_TO_SESSION_URL + "appid=" + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        return response.toString();
    }
    
    
    public static String getWxUserInfo( String token, String openid ) {
    	//String url = "https://api.weixin.qq.com/sns/userinfo?"
    	//		+ "access_token=" + "84_XoBE1O8SoLHwG-b5X6wd-6Z_wciThM5rsI_fBtI5sljp-Mi6ecALvGVfTd-IBNDfSW7vnKzFzOrsJ8TdbMnnhkYgmfDqbhInCWrlLC3Q9jo"
    	//		+ "&openid=" + "oRrdQtyavhLmLVlfFEgAraqTnomE";
    	String url = "https://api.weixin.qq.com/sns/userinfo?"
    			+ "access_token=" + token + "&openid=" + openid;
    	try {
	    	URL obj = new URL(url);
	        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
	        con.setRequestMethod("GET");
	        // 设置连接超时为5秒
	        con.setConnectTimeout(20000);
	        // 设置读取超时为10秒
	        con.setReadTimeout(20000);
	        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
	        String inputLine;
	        StringBuffer response = new StringBuffer();
	        while ((inputLine = in.readLine()) != null) {
	            response.append(inputLine);
	        }
	        in.close();
	        return response.toString();
    	} catch ( Exception e) {
			e.printStackTrace();
			throw new MyException("调用微信获取用户信息异常");
		}
    }

    public static void main(String[] args) throws IOException {
        String appid = "wxe66dcbb285ee1076";
        String secret = "98ff9a8af0bb63ba267d52195f78b540";
        String code = "093HMj1w3O9Ey33LM84w3ltd5L1HMj1d";

        //String result = jscode2session(appid, secret, code);
        //System.out.println(result);
        String result = getWxUserInfo(appid, code);
        System.out.println(result);
    }
}



